using System.Collections.Generic;
using UnityEngine;

public class CrowAI : MonoBehaviour
{

    private int m = 1;//质量
    public float speed = 3;
    private Vector3 velocity = Vector3.forward * 5;
    private Vector3 startVelocity;
    public Transform target;

    [Header("Movement Constraints")]
    public bool lockRotation = true; // 锁定旋转
    public bool moveAlongZ = true;  // 沿Z轴移动
    public bool moveAlongX = true; // 沿Y轴移动

    private Vector3 sumForce = Vector3.zero;//合力
    private Vector3 separateForce = Vector3.zero;//分离的力
    public List<GameObject> separateNeighbors = new List<GameObject>();
    public int separationDistance = 3;
    public float separationWeight = 1;//分离力权重

    private Vector3 alignmentForce = Vector3.zero;//队列的力
    public List<GameObject> alignmentNeighbors = new List<GameObject>();
    public int alignmentDistance = 6;
    public float alignmentWeight = 1;//队列力权重

    private Vector3 gatherForce = Vector3.zero;//聚集的力
    public float gatherWeight = 1;//聚集力权重

    private float checkIntarval = 0.2f;//检测间隔

    private void Start()
    {
        // 确保目标对象存在且名称匹配
        if (target == null)
        {
            target = GameObject.Find("target")?.transform;
            if (target == null)
            {
                Debug.LogError("Target object not found! Creating one...");
                target = new GameObject("target").transform;
                target.position = new Vector3(0, 5, 20); // 设置初始位置
            }
        }
        startVelocity = velocity;
        InvokeRepeating("CalcForce", 0, checkIntarval);
    }

    void CalcForce()
    {
        sumForce = Vector3.zero;
        separateForce = Vector3.zero;
        alignmentForce = Vector3.zero;
        gatherForce = Vector3.zero;
        //计算分离的力
        separateNeighbors.Clear();
        Collider[] colliders = Physics.OverlapSphere(this.transform.position, separationDistance);//获得周围的物体
        foreach (Collider item in colliders)
        {
            if (item != null && item.gameObject != this.gameObject)
            {
                separateNeighbors.Add(item.gameObject);
            }
        }

        foreach (GameObject item in separateNeighbors)
        {
            Vector3 dir = transform.position - item.transform.position;
            separateForce += dir.normalized / dir.magnitude;
        }
        if (separateNeighbors.Count > 0)
        {
            separateForce *= separationWeight;

            sumForce += separateForce;
        }
        //计算队列的力
        alignmentNeighbors.Clear();
        colliders = Physics.OverlapSphere(transform.position, alignmentDistance);
        foreach (Collider item in colliders)
        {
            if (item != null && item.gameObject != this.gameObject)
            {
                alignmentNeighbors.Add(item.gameObject);
            }
        }
        Vector3 avgDir = Vector3.zero;
        foreach (GameObject item in alignmentNeighbors)
        {
            avgDir += item.transform.forward;
        }
        if (alignmentNeighbors.Count > 0)
        {
            avgDir /= alignmentNeighbors.Count;
            alignmentForce = avgDir - transform.forward;
            alignmentForce *= alignmentWeight;
            sumForce += alignmentForce;
        }

        //计算聚集的力
        //if (separateNeighbors.Count > 0 || alignmentNeighbors.Count <= 0) return;//当进行分离操作或周围无同类物体时不产生聚集的力
        if (alignmentNeighbors.Count > 0)
        {
            Vector3 center = Vector3.zero;
            foreach (GameObject item in alignmentNeighbors)
            {
                center += item.transform.position;
            }
            center /= alignmentNeighbors.Count;
            Vector3 DirToCenter = center - this.transform.position;
            gatherForce += DirToCenter;
            gatherForce *= gatherWeight;
            sumForce += gatherForce;
        }
        //保持恒定飞行速度的力
        Vector3 engineForce = velocity.normalized * startVelocity.magnitude;
        sumForce += engineForce * 0.1f;
        //朝目标飞行
        Vector3 targetDir = target.position - transform.position;
        sumForce += (targetDir.normalized - transform.forward) * speed;

    }

    private void Update()
    {
        Vector3 a = sumForce / m;//计算加速度
        velocity += a * Time.deltaTime;
        // 应用移动约束
        Vector3 constrainedVelocity = velocity;

        if (moveAlongZ && !moveAlongX)
        {
            constrainedVelocity = new Vector3(0, 0, velocity.z); // 只沿Z轴移动
        }
        else if (moveAlongX && !moveAlongZ)
        {
            constrainedVelocity = new Vector3(velocity.x, 0, 0); // 只沿Y轴移动
        }
        else if (moveAlongZ && moveAlongX)
        {
            constrainedVelocity = new Vector3(velocity.x, 0, velocity.z); // 沿Y和Z轴移动
        }
        else
        {
            constrainedVelocity = Vector3.zero; // 不移动
        }

        // 更新位置
        transform.Translate(constrainedVelocity * Time.deltaTime, Space.World);
        if (lockRotation)
        {
            transform.rotation = Quaternion.identity; // 保持无旋转
        }

        //transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(velocity), Time.deltaTime * 3);

        ////transform.Translate(transform.forward * Time.deltaTime * velocity.magnitude, Space.World);
    }

}